<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
    const flat = [
        {id: 1, name: "部门1", pid: 0},
        {id: 2, name: "部门2", pid: 1},
        {id: 3, name: "部门3", pid: 1},
        {id: 4, name: "部门4", pid: 3},
        {id: 5, name: "部门5", pid: 4}
    ]

    let tree = []

    let parent = flat.filter(item => item.pid === 0)
    let children = flat.filter(item => item.pid !== 0)

    const result = dataToTree(parent, children)
    console.log(result)

    function dataToTree(parent, children) {
        parent.map(p => {
            children.map((c, i) => {
                if (p.id === c.pid) {
                    let _children = JSON.parse(JSON.stringify(children))
                    _children.splice(i, 1)
                    dataToTree([c], _children)
                    if (p.children) {
                        p.children.push(c)
                    } else {
                        p.children = [c]
                    }
                }
            })
        })

        return parent
    }

</script>
</body>
</html>